package mtn.bowen.yan.server.controller;

import com.jfoenix.controls.JFXBadge;
import com.jfoenix.controls.JFXButton;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import mtn.bowen.yan.server.fx.FxmlView;
import mtn.bowen.yan.server.fx.StageManager;
import mtn.bowen.yan.server.service.MainService;
import mtn.bowen.yan.server.service.MenuManagementService;
import mtn.bowen.yan.server.utils.LoadingUtils;
import mtn.bowen.yan.server.utils.Platform;
import mtn.bowen.yan.server.utils.ResourceBundleUtil;
import org.controlsfx.control.PopOver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;


/**
 * @author <a href=mailto:yanbowen90@foxmail.com> bowen.yan </a>
 * @version 1.0
 * @description: 主界面
 * @date 2021-10-21 11:55 PM
 */
@Component
public class MainController extends BaseController implements Initializable {

    private final static Logger LOGGER = LoggerFactory.getLogger(MainController.class);

    @FXML
    public VBox sideBar;
    @FXML
    private VBox views;
    @FXML
    public ScrollPane body;
    @FXML
    public Label title;
    @FXML
    private ScrollPane scroll;

    @FXML
    private Button recipeManagement;
    @FXML
    private Button home;
    @FXML
    private Button about;
    @FXML
    private Button webview;
    @FXML
    private Button hamburger;

    @FXML
    private StackPane root;
    @FXML
    private JFXButton config;
    @FXML
    private VBox drawer;
    @FXML
    private JFXBadge messages;
    @FXML
    private JFXBadge notifications;
    @FXML
    private JFXBadge bg_info;

    public static final PopOver popConfig = new PopOver();
    public static final PopOver popup = new PopOver();

    private ObservableList<Button> items = FXCollections.observableArrayList();

    boolean scrolling = false;

    private Parent popContent;
    public static MainController ctrl;

    @Resource
    private MainService mainService;

    @Resource
    private LoadingUtils loadingUtils;

    @Resource
    private MenuManagementService menuManagementService;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        ctrl = this;
        loadContentPopup();

        populateItems();

//         about();

        try {
            addSubPop();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //存储主界面StackPane
        StageManager.putParentStackPaneMap("parentStackPane", root);

    }

    @FXML
    private void altLayout() {

        int minimum = 70;
        int max = 250;

        if (drawer.getPrefWidth() == max) {

            drawer.setPrefWidth(minimum);

            for (Node node : views.getChildren()) {
                if (node instanceof Button) {
                    ((Button) node).setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
                    ((Button) node).setAlignment(Pos.BASELINE_CENTER);
                } else if (node instanceof TitledPane) {
                    ((TitledPane) node).setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
                    ((TitledPane) node).setAlignment(Pos.BASELINE_CENTER);
                    ((TitledPane) node).setExpanded(false);
                    ((TitledPane) node).setCollapsible(false);
                } else {
                    break;
                }
            }

            addEvents();
        } else {
            drawer.setPrefWidth(max);
            for (Node node : views.getChildren()) {
                if (node instanceof Button) {
                    ((Button) node).setContentDisplay(ContentDisplay.LEFT);
                    ((Button) node).setAlignment(Pos.BASELINE_LEFT);
                } else if (node instanceof TitledPane) {
                    ((TitledPane) node).setContentDisplay(ContentDisplay.RIGHT);
                    ((TitledPane) node).setAlignment(Pos.BASELINE_RIGHT);
                    ((TitledPane) node).setCollapsible(true);
                } else {
                    break;
                }
            }
        }
    }

    private void addEvents() {
        VBox drawerContent;

        for (Node node : drawer.getChildren()) { // root
            if (node instanceof ScrollPane) {

                drawerContent = (VBox) ((ScrollPane) node).getContent();

                for (Node child : drawerContent.getChildren()) {
                    if (child instanceof Button) {
                        child.setOnMouseEntered(e -> {
                            popup.setAutoHide(true);
                            if (popup.isShowing()) {
                                popup.hide();
                            }
                        });
                    } else if (child instanceof TitledPane) {
                        addEvent(child);
                    }
                }
            } else {
                // for others layouts
            }
        }
    }

    private void addSubPop() throws Exception {

        ResourceBundle bundle = ResourceBundleUtil.getResource();
        popup.setContentNode(FXMLLoader.load(getClass().getResource("/template/main/Popover.fxml"), bundle));

//        popup.getRoot().getStylesheets().add(getClass().getResource("/com/gn/theme/css/poplight.css").toExternalForm());

        popup.setArrowLocation(PopOver.ArrowLocation.LEFT_CENTER);
        popup.setArrowIndent(0);
        popup.setArrowSize(0);
        popup.setCornerRadius(0);
        popup.setAutoFix(true);
    }

    private void addEvent(Node node) {
        popup.setDetached(false);
        popup.setDetachable(false);
        popup.setCloseButtonEnabled(false);
        popup.setArrowSize(0);
        popup.setHeaderAlwaysVisible(false);

        ScrollPane scrollPane = new ScrollPane();
        scrollPane.getStylesheets().add(getClass().getResource("/styles/theme/custom-scroll.css").toExternalForm());

        VBox v = new VBox();
        v.setPrefWidth(200);

        TitledPane pane = (TitledPane) node;
        VBox vbox = (VBox) pane.getContent();

        for (Node btn : vbox.getChildren()) {
            String text = ((Button) btn).getText();
            Button button = new Button(text);
            button.setPrefWidth(v.getPrefWidth());
            button.setOnMouseClicked(e -> {
//                body.setContent(ViewManager.getInstance().get(button.getText().toLowerCase()));
//                title.setText(button.getText());
//                popup.hide();
            });
            button.setMinHeight(40);
            v.getChildren().add(button);
        }

//        Popover.ctrl.options.getChildren().clear();

        node.setOnMouseEntered((Event e) -> {
            if (drawer.getPrefWidth() == 70) {
                PopoverController.ctrl.options.getChildren().setAll(v);
                popup.show(pane, -1);
            }
        });
    }

    private void populateItems() {
        for (Node node : views.getChildren()) {
            if (node instanceof Button) {
                items.add((Button) node);
            }
        }
    }

    private void loadContentPopup() {
        try {
            ResourceBundle bundle = ResourceBundleUtil.getResource();
            popContent = FXMLLoader.load(getClass().getResource("/template/main/Config.fxml"), bundle);
            popConfig.getRoot().getStylesheets()
                    .add(getClass().getResource("/styles/theme/poplight.css").toExternalForm());
            popConfig.setContentNode(popContent);
            popConfig.setArrowLocation(PopOver.ArrowLocation.TOP_RIGHT);
            popConfig.setArrowIndent(0);
            popConfig.setArrowSize(0);
            popConfig.setCornerRadius(0);
            popConfig.setAutoFix(true);
            popConfig.setAnimated(false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void openConfig() {
        if (popConfig.isShowing()) {
            popConfig.hide();
        } else {
            popConfig.show(config, 0);
            popConfig.getRoot().setFocusTraversable(true);
        }
    }

    /**
     * 菜品菜单管理
     */
    @FXML
    private void recipeMenuManagement() {

        //开始执行Loading界面、并设置解除等待标记
        StageManager.putParentLoadMap("ParentLoad", loadingUtils.loading(StageManager.getParentStackPaneMap("parentStackPane")));
        StageManager.getExecutor().execute(() -> {
            Platform.runLater(() -> {
                mainService.updateBody(FxmlView.MODULE_MENU_MANAGEMENT, title, body);
                loadingUtils.remove(StageManager.getParentStackPaneMap("parentStackPane"), StageManager.getParentLoadMap("ParentLoad"));
            });
        });
    }

    /**
     * 食谱管理
     * <p>
     * 构建页面代码SpringUtils.getBean(StageManager.class).switchContent(view, body);
     */
    @FXML
    public void mainRecipeManagement() {

        //开始执行Loading界面、并设置解除等待标记
        StageManager.putParentLoadMap("ParentLoad", loadingUtils.loading(StageManager.getParentStackPaneMap("parentStackPane")));
        StageManager.getExecutor().execute(() -> {
            Platform.runLater(() -> {
                mainService.updateBody(FxmlView.MODULE_RECIPE_MANAGEMENT, title, body);
                loadingUtils.remove(StageManager.getParentStackPaneMap("parentStackPane"), StageManager.getParentLoadMap("ParentLoad"));
            });
        });
    }

    /**
     * 本周食谱
     */
    @FXML
    public void mainWeekRecipe() {
        //开始执行Loading界面、并设置解除等待标记
        StageManager.putParentLoadMap("ParentLoad", loadingUtils.loading(StageManager.getParentStackPaneMap("parentStackPane")));
        StageManager.getExecutor().execute(() -> {
            Platform.runLater(() -> {
                mainService.updateBody(FxmlView.MODULE_WEEK_RECIPE, title, body);
                loadingUtils.remove(StageManager.getParentStackPaneMap("parentStackPane"), StageManager.getParentLoadMap("ParentLoad"));
            });
        });
    }

    /**
     * 菜品排名
     */
    @FXML
    private void foodRanking() {
        //开始执行Loading界面、并设置解除等待标记
        StageManager.putParentLoadMap("ParentLoad", loadingUtils.loading(StageManager.getParentStackPaneMap("parentStackPane")));
        StageManager.getExecutor().execute(() -> {
            Platform.runLater(() -> {
                mainService.updateBody(FxmlView.MODULE_FOOD_RANKING, title, body);
                loadingUtils.remove(StageManager.getParentStackPaneMap("parentStackPane"), StageManager.getParentLoadMap("ParentLoad"));
            });
        });
    }

    /**
     * 投票建议
     */
    @FXML
    public void pollsSuggest() {
        //开始执行Loading界面、并设置解除等待标记
        StageManager.putParentLoadMap("ParentLoad", loadingUtils.loading(StageManager.getParentStackPaneMap("parentStackPane")));
        StageManager.getExecutor().execute(() -> {
            Platform.runLater(() -> {
                mainService.updateBody(FxmlView.MODULE_POLLS_SUGGEST, title, body);
                loadingUtils.remove(StageManager.getParentStackPaneMap("parentStackPane"), StageManager.getParentLoadMap("ParentLoad"));
            });
        });
    }

    private PopOver pop = new PopOver();

    @FXML
    private void openMessages() {
        if (!pop.isShowing()) {

            Separator top = new Separator();
            Separator bottom = new Separator();

            Label message = new Label("Messages");
            Label count = new Label("4 News");
            count.getStyleClass().add("text-success");
            GridPane title = new GridPane();
            title.setMinHeight(40D);

            title.setAlignment(Pos.CENTER);
            title.add(message, 0, 0);
            title.add(count, 1, 0);
            GridPane.setHalignment(count, HPos.RIGHT);

            ListView<Node> listView = new ListView<>();

//            listView.getItems().addAll(list);
            listView.getStyleClass().add("border-0");

            Button btn = new Button("Read all messages");
            btn.getStyleClass().add("btn-flat");

            VBox root = new VBox(title, top, listView, bottom, btn);
            root.setAlignment(Pos.CENTER);
            root.setPrefSize(300, 300);
            title.setPrefWidth(root.getPrefWidth());
            count.setPrefWidth(root.getPrefWidth());
            message.setPrefWidth(root.getPrefWidth());
            count.setAlignment(Pos.CENTER_RIGHT);
            title.setPadding(new Insets(0, 25, 0, 25));
            btn.setPrefWidth(root.getPrefWidth());

//            listView.getStylesheets().add(getClass().getResource("/styles/theme/css/custom-scroll.css").toExternalForm());

            pop.getRoot().getStylesheets().add(getClass().getResource("/styles/theme/poplight.css").toExternalForm());
            pop.setContentNode(root);
            pop.setArrowLocation(PopOver.ArrowLocation.TOP_RIGHT);
            pop.setArrowIndent(0);
            pop.setArrowSize(0);
            pop.setCloseButtonEnabled(false);
            pop.setHeaderAlwaysVisible(false);
            pop.setCornerRadius(0);
            pop.setAutoFix(true);
            pop.show(messages);

        } else {
            pop.hide();
        }
    }

    @FXML
    private void openNotification() {
        if (!pop.isShowing()) {

            Separator top = new Separator();
            Separator bottom = new Separator();

            Label message = new Label("Messages");
            Label count = new Label("4 News");
            count.getStyleClass().add("text-success");
            GridPane title = new GridPane();
            title.setMinHeight(40D);

            title.setAlignment(Pos.CENTER);
            title.add(message, 0, 0);
            title.add(count, 1, 0);
            GridPane.setHalignment(count, HPos.RIGHT);

            ListView<Node> listView = new ListView<>();

//            listView.getItems().addAll(list);
            listView.getStyleClass().add("border-0");

            Button btn = new Button("Read all messages");
            btn.getStyleClass().add("btn-flat");

            VBox root = new VBox(title, top, listView, bottom, btn);
            root.setAlignment(Pos.CENTER);
            root.setPrefSize(300, 300);
            title.setPrefWidth(root.getPrefWidth());
            count.setPrefWidth(root.getPrefWidth());
            message.setPrefWidth(root.getPrefWidth());
            count.setAlignment(Pos.CENTER_RIGHT);
            title.setPadding(new Insets(0, 25, 0, 25));
            btn.setPrefWidth(root.getPrefWidth());

            listView.getStylesheets().add(getClass().getResource("/styles/theme/custom-scroll.css").toExternalForm());

            pop.getRoot().getStylesheets().add(getClass().getResource("/styles/theme/poplight.css").toExternalForm());
            pop.setContentNode(root);
            pop.setArrowLocation(PopOver.ArrowLocation.TOP_RIGHT);
            pop.setArrowIndent(0);
            pop.setArrowSize(0);
            pop.setCloseButtonEnabled(false);
            pop.setHeaderAlwaysVisible(false);
            pop.setCornerRadius(0);
            pop.show(notifications);

        } else {
            pop.hide();
        }
    }

}

